//
//  MyInfoViewController.m
//  IM_LearningGYDF
//
//  Created by gydf on 16/10/19.
//  Copyright © 2016年 mac. All rights reserved.
//

#import "MyInfoViewController.h"
#import "MyInfoHeadViewCell.h"
#import "PersonCenterTableViewCell.h"
#import "UploadParam.h"
#import "ChangePasswordViewController.h"
#import "BasicModel.h"
#import "UserHeadImageModel.h"
#import <AssetsLibrary/ALAsset.h>

#import <AssetsLibrary/ALAssetsLibrary.h>

#import <AssetsLibrary/ALAssetsGroup.h>

#import <AssetsLibrary/ALAssetRepresentation.h>


#define uploadPicInfo @"uploadPicInfo"
#define updateUserInfo @"updateUserInfo"

@interface MyInfoViewController ()<UITableViewDelegate,UITableViewDataSource,UIActionSheetDelegate,UIAlertViewDelegate,UINavigationControllerDelegate,UIImagePickerControllerDelegate>
{
    UITableView *_tableView;
    UIImage *_image;//选择的图片
    UIImageView *_headImageView;//用户头像
    UserHeadImageModel *_imageModel;//头像model
}
@property(nonatomic,strong)NSArray * infoArray;
@property(nonatomic,strong)NSMutableArray * detailArray;
@property(nonatomic,strong)NSArray * currentArray;
@end

@implementation MyInfoViewController
-(NSArray *)infoArray{
    if (!_infoArray) {
        _infoArray = @[@"头像",@"密码修改"];
    }
    return _infoArray;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setLeftBackNavigation];
    [self setRightBackNavigation];
    [self setNavigationTitle:@"个人设置"];
    [self creatView];
    //[self sendRequest];
    //self.currentArray = [MyControl getAccountMore];
    // Do any additional setup after loading the view.
}
//-(void)sendRequest{
//    NSString * api= [NSString stringWithFormat:@"api/User/GetAccInfo?token=%@",[MyControl getUserToken]];
//    [HttpRequest getWithURLString:URL(api) parameters:nil success:^(id responseObject) {
//        _infoModel = [[PersonModel alloc]initWithResponse:responseObject];
//        if(_infoModel.status.intValue == 1){
//
//            [_tableView reloadData];
//            
//        }else if(_infoModel.status.intValue == 0){
//
//        }
//    } failure:^(NSError *error) {
//        
//    }];
//}
#pragma mark -creatTableView
- (void)creatView{
    _tableView=[[UITableView alloc]initWithFrame:CGRectMake(0, 0, IPHONE_WIDTH, IPHONE_HEIGHT-64)style:UITableViewStylePlain];
    _tableView.delegate=self;
    _tableView.dataSource=self;
    _tableView.tableFooterView = [UIView new];
    _tableView.scrollEnabled=NO;
    //取消下划线
    _tableView.separatorStyle=UITableViewCellSeparatorStyleNone;
    [self.view addSubview:_tableView];
}

#pragma mark -tableViewDelegate
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return self.infoArray.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return 1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section==0) {
        MyInfoHeadViewCell *cell=[[MyInfoHeadViewCell alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:@"firstCell"];
        cell.accessoryType=UITableViewCellAccessoryDisclosureIndicator;
        [cell.headImage setImageWithURL:[NSURL URLWithString:_imageStr] placeholderImage:[UIImage imageNamed:@"k_portrait@2x"]];
        _headImageView=cell.headImage;
        
        return cell;
    }else{
        NSString *cellID=@"cellID";
        PersonCenterTableViewCell *cell=[[PersonCenterTableViewCell alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:cellID];
        cell.contentView.backgroundColor=[UIColor whiteColor];
//        cell.nameLabel.text = self.infoArray[indexPath.row];
        cell.myTitle.text = @"修改密码";
        cell.myTitle.textColor=[UIColor blackColor];
        cell.headImageView.image=[UIImage imageNamed:@"k_password@2x"];

//        cell.titleLabel.text = [MyControl getAccountNowName];
        cell.accessoryType=UITableViewCellAccessoryDisclosureIndicator;
        
        UILabel *line=[[UILabel alloc]initWithFrame:CGRectMake(0, 59, IPHONE_WIDTH, 1)];
        line.backgroundColor=BACKCOLOR_GRAY;
        [cell.contentView addSubview:line];
        return cell;
    }
    return nil;
}
-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:YES];
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section==0) {
        return 76;
    }
    return 60;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    if (section==0) {
        return 0;
    }
    return 30;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section==0) {
        [self uploadPhoto];
    }else if (indexPath.section==1){
        ChangePasswordViewController *password=[[ChangePasswordViewController alloc]init];
        [self.navigationController pushViewController:password animated:YES];
    }
}

#pragma mark -相册

- (void)uploadPhoto{
    if (IOS_VERSION_8_OR_LATER)
    {//alertcontroller是IOS8的东西
        // NSString *title = NSLocalizedString(@"头像上传", nil);
        //    NSString *message = NSLocalizedString(@"A message should be a short, complete sentence.", nil);
        NSString *cancelButtonTitle = NSLocalizedString(@"取消", nil);
        NSString *otherButtonTitle = NSLocalizedString(@"相册", nil);
        //        NSString *otherButtonTitle2 = NSLocalizedString(@"拍照", nil); 不支持拍照
        NSString *otherButtonTitle2 = NSLocalizedString(@"拍照", nil);
        
        UIAlertController *alertController = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
        
        // Create the actions.
       UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:cancelButtonTitle style:UIAlertActionStyleCancel handler:^(UIAlertAction *action)
      {
          //cancel Button
      }];
        __weak MyInfoViewController *myWeakSelf=self;
        //相册
        UIAlertAction *otherAction = [UIAlertAction actionWithTitle:otherButtonTitle style:UIAlertActionStyleDefault handler:^(UIAlertAction *action)
      {
          
//          NSLog(@"The \"Okay/Cancel\" alert's other action occured.");
          
          if (![UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeSavedPhotosAlbum])
          {
              //如果当前
              return;
          }
          UIImagePickerController *imagePickerController=[[UIImagePickerController alloc]init];
          imagePickerController.sourceType=UIImagePickerControllerSourceTypeSavedPhotosAlbum;
          imagePickerController.delegate = myWeakSelf;
          imagePickerController.allowsEditing=YES;
          [self presentViewController:imagePickerController animated:NO completion:nil];
      }];
        
//        UIAlertAction *seeBigImgAction = [UIAlertAction actionWithTitle:otherButtonTitle2 style:UIAlertActionStyleDefault handler:^(UIAlertAction * action)
//      {
//          NSLog(@"here is bigImg Btn");
////            if (_photoURL==nil||_photoURL.length==0) {
////                return ;
////            }
////            PhotoImageViewController *photo=[[PhotoImageViewController alloc]init];
////            photo.photoImageURL=_photoURL;
////            [self.navigationController pushViewController:photo animated:YES];
//      }];
        
        
        UIAlertAction *otherAction2 = [UIAlertAction actionWithTitle:otherButtonTitle2 style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
//            NSLog(@"The \"Okay/Cancel\" alert's other action occured.");
            if (![UIImagePickerController isCameraDeviceAvailable:UIImagePickerControllerCameraDeviceRear]) {
                [LZXHelper postMessageWithText:@"您的手机还不支持照相功能！" View:self.view];
            }
            UIImagePickerController *imagePickerController=[[UIImagePickerController alloc]init];
            imagePickerController.sourceType=UIImagePickerControllerSourceTypeCamera;
            imagePickerController.delegate=myWeakSelf;
            imagePickerController.allowsEditing=YES;
            [self presentViewController:imagePickerController animated:NO completion:nil];
        }];
        
        
        // Add the actions.
        [alertController addAction:otherAction];
        //[alertController addAction:otherAction2];  不支持拍照
        [alertController addAction:cancelAction];
        [alertController addAction:otherAction2];
        
        [self presentViewController:alertController animated:YES completion:nil];
        
        
    }
    else if(IOS_VERSION_7_OR_LATER)
    {
        
        UIAlertView *alertView=[[UIAlertView alloc]initWithTitle:nil message:nil delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"相册",@"拍照", nil];
        [alertView show];
    }
}


#pragma mark -相册Delegate

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info{
    //编辑时调用
    if (info[@"UIImagePickerControllerEditedImage"])
    {
        _image=info[@"UIImagePickerControllerEditedImage"];
    }
    
//    __block NSString* imageFileName;
    
    
//    NSURL *imageURL = [info valueForKey:UIImagePickerControllerReferenceURL];
//    
//    ALAssetsLibraryAssetForURLResultBlock resultblock = ^(ALAsset *myasset)
//    
//    {
//        
//        ALAssetRepresentation *representation = [myasset defaultRepresentation];
//        
//        imageFileName = [representation filename];
//        
//    };
//      ALAssetsLibrary* assetslibrary = [[ALAssetsLibrary alloc] init];
//    [assetslibrary assetForURL:imageURL
//                   resultBlock:resultblock
//                  failureBlock:nil];
//    NSString *imagePath = [imageFileName componentsSeparatedByString:@"."];
    //[NSThread detachNewThreadSelector:@selector(uploadPhotoImage) toTarget:self withObject:nil];
    NSThread* myThread = [[NSThread alloc] initWithTarget:self
                                                 selector:@selector(uploadPhotoImage)
                                                   object:nil];
    [myThread start];
    [picker dismissViewControllerAnimated:YES completion:nil];
    
}
- (void)uploadPhotoImage{
    if (!_image) {
        return;
    }
//    [self.view addSubview:self.centerIndicator];
//    [self.centerIndicator startAnimating];
    NSData *date = UIImageJPEGRepresentation(_image, 0.5);
    NSString * imageStr = [date base64EncodedStringWithOptions:NSDataBase64Encoding64CharacterLineLength];
//    NSString *token=[[NSUserDefaults standardUserDefaults]objectForKey:@"Token"];
//    NSIndexPath * selectedIndex = [_tableView indexPathForSelectedRow];
//    MyInfoHeadViewCell * cell = [_tableView cellForRowAtIndexPath:selectedIndex];
//    //NSString * sourcePath = [MyControl storeImagePath];
//    PersonCenterViewController * pc = (PersonCenterViewController *)self.PersonVC;
    //
        
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    
    [formatter setDateFormat:@"yyyyMMddHHmmssSSS"];
    //以时间为照片命名
    NSString *timestamp = [[formatter stringFromDate:[NSDate date]] stringByAppendingString:@".jpg"];

    
    NSDictionary *dict=@{
                         @"picName":timestamp,
                         @"picBase":imageStr,
                         @"picType":@"empPic",
                         };
    
    NSMutableDictionary *picList=[NSMutableDictionary new];
    NSMutableArray *imageArr=[NSMutableArray new];
    [imageArr addObject:dict];
    [picList setObject:imageArr forKey:@"picList"];
    //   字典转json
    NSData* jsonData = [NSJSONSerialization dataWithJSONObject:picList options:NSJSONWritingPrettyPrinted error:nil];
    NSString* str = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    //拼接soap字符串
    NSString* soap = [NSString stringWithFormat:@"<sessionId>%@</sessionId>\n<content>%@</content>",[LZXHelper getSessionID],str];
    
    [LZXHelper postLoadViewWithText:HUD_PLEASEWAIT View:self.view];
    
    [HttpRequest SOAPData:[LZXHelper getServerURL] SoapMthod:uploadPicInfo soapBody:soap success:^(id responseObject) {
        [LZXHelper hideLoadViewWithView:self.view];
        //解析数据并保存用户数据
        //NSLog(@"%@",responseObject[@"msg"]);
        _imageModel=[[UserHeadImageModel alloc]initWithResponse:responseObject];
        if ([_imageModel.code isEqualToString:@"200"]) {
            [self updateUserInfoRequest];
        }else if([_imageModel.code isEqualToString:@"220"]){
            [LZXHelper postMessageWithText:_imageModel.msg View:self.view];
        }

    } failure:^(NSError *error) {
                [LZXHelper hideLoadViewWithView:self.view];
    }];

}
#pragma mark - 更新用户信息
- (void)updateUserInfoRequest{
    //取第一个图片
    if (_imageModel.dataArr.count==0) {
        return;
    }
    UserHeadImageModel *headModel=_imageModel.dataArr[0];
    NSDictionary *dict=@{
                         @"oldPassword":@"",
                         @"newPassword":@"",
                         @"newPhoneNumber":@"",
                         @"newMailBox":@"",
                         @"operateType":@"3",
                         @"newEmpPic":headModel.picPath?headModel.picPath:@""
                         //                        @"reqStr":@"weaqtfaw"
                         };
    
    //   字典转json
    NSData* jsonData = [NSJSONSerialization dataWithJSONObject:dict options:NSJSONWritingPrettyPrinted error:nil];
    NSString* str = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    //拼接soap字符串
    NSString* soap = [NSString stringWithFormat:@"<sessionId>%@</sessionId>\n<content>%@</content>",[LZXHelper getSessionID],str];
    [LZXHelper postLoadViewWithText:HUD_PLEASEWAIT View:self.view];
    [HttpRequest SOAPData:[LZXHelper getServerURL] SoapMthod:updateUserInfo soapBody:soap success:^(id responseObject) {
        [LZXHelper hideLoadViewWithView:self.view];
        
        //解析数据
        BasicModel *model=[[BasicModel alloc]initWithResponse:responseObject];
        if ([model.code isEqualToString:@"200"]) {
            [LZXHelper postMessageWithText:model.msg View:self.view];
//            _headImageView.image=_image;
            [_headImageView setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@%@",headModel.picUrl,headModel.picPath]]];
            [[NSNotificationCenter defaultCenter]postNotificationName:@"userHeadImageChanged" object:nil];
        }else if([model.code isEqualToString:@"220"]){
            [LZXHelper postMessageWithText:model.msg View:self.view];
        }
    } failure:^(NSError *error) {
            [LZXHelper hideLoadViewWithView:self.view];
    }];
}

-(void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:YES];
    //[pc updateAccountImage];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
